package ma.myschool.app.webapp.action;

import java.io.Serializable;

import ma.myschool.app.model.Classe;
import ma.myschool.app.service.ClasseManager;

import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;

@Component("classeForm")
@Scope("request")
public class ClasseForm extends BasePage implements Serializable {
    private ClasseManager classeManager;
    private Classe classe = new Classe();
    private Long id;

    @Autowired
    public void setClasseManager(@Qualifier("classeManager") ClasseManager classeManager) {
        this.classeManager = classeManager;
    }

    public Classe getClasse() {
        return classe;
    }

    public void setClasse(Classe classe) {
        this.classe = classe;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String delete() {
    	try {
    		id = getParameter("id") != null ? new Long(getParameter("id")) : null;
            classeManager.remove(id);
            addMessage("classe.deleted");
		} catch (DataIntegrityViolationException e) {
			addError(getText("errors.use.already"));
		}
    	

        return "success";
    }

    public String edit() {
        // Workaround for not being able to set the id using #{param.id} when using Spring-configured managed-beans
        if (id == null) {
        	id = getParameter("id") != null ? new Long(getParameter("id")) : null;
        }
        // Comparison to zero (vs. null) is required with MyFaces 1.2.2, not with previous versions
        if (id != null && id != 0) {
            classe = classeManager.get(id);
        } else {
            classe = new Classe();
        }

        return "editClasse";
    }

    public String save() {
        boolean isNew = (classe.getId() == null || classe.getId() == 0);
        classeManager.save(classe);

        String key = (isNew) ? "classe.added" : "classe.updated";
        addMessage(key);

        if (isNew) {
            return "list";
        } else {
            return "edit";
        }
    }
} 